# coding=utf-8

"""
Author: zhangzheng
Description: 
Version: 0.0.1
LastUpdateDate: 
UpadteURL: 
LOG: 
"""

from flask_login import current_user
from typing import Iterable, Tuple, Dict
import json
import os

from app.cores.dictionaries import CONTENT_TYPE


def handle_params(params):
    """处理请求参数，使其满足get请求查询字符串"""
    ret = {}
    if isinstance(params, Iterable):
        for param in params:
            if param.name_ in ret.keys():
                ret[param.name_].append(param.value_)
            else:
                ret[param.name_] = [param.value_]
    return ret


def handle_headers(headers):
    """
    处理请求头数据
    :param headers: 请求头数据
    :type headers: List[HTTPCaseHeader]
    """
    ret = {}
    for header in headers:
        ret[header.name_] = header.value_
    return ret


def handle_data_from_params(params):
    """
    处理请求参数，使其满足post请求的数据格式
    :param params: 参数数据
    :type params: Iterable[HTTPCaseParameter]
    :return: 处理后的参数数据
    :rtype: Dict
    """
    if isinstance(params, Iterable):
        # return tuple((param.name_, param.value_) for param in params)
        return {param.name_: param.value_ for param in params}


def handle_data_for_content_type(params, content_type=None):
    """
    处理请求参数，使其满足post请求的数据格式
    :param params: 参数数据
    :type params: Iterable[HTTPCaseParameter]
    :param content_type: HTTP请求体数据类型
    :type content_type: str
    :return: 处理后的参数数据
    :rtype: Dict
    """
    if isinstance(params, Iterable):
        if content_type == CONTENT_TYPE.FORM_DATA:
            return {param.name_: param.value_ for param in params}


def handle_data_form_json_str(json_str):
    """
    处理消息体json字符串，转为py对象
    :param json_str: json字符串
    :type json_str: str
    :return: py对象
    """
    return json.loads(json_str)


def handle_url(protocol, domain, port, path):
    """预处理并返回url"""
    protocol = protocol.strip()
    domain = domain.strip()
    port = port.strip()
    path = path.strip()
    if port:
        return protocol + "://" + domain + ":" + port + path
    else:
        return protocol + "://" + domain + path


def handle_file_upload(file_upload):
    """
    处理文件上传参数
    :param file_upload: 文件上传参数
    :type file_upload: Iterable[HTTPCaseFileUpload]
    """

    if file_upload:
        return {row.name_: open(row.value_, 'rb') for row in file_upload}
    return None


def render_dict_to_html(d: dict):
    """将字典解析为html样式内容，供前端展示"""
    ret = ''
    for k, v in d.items():
        ret += str(k) + ':' + str(v) + '<br>'
    return ret


def save_binary_to_file(bytes, file_name):
    """将二进制内容存储到文件"""
    from app.config import attachment_dir
    user_id = current_user.id
    attachment_user_dir = os.path.join(attachment_dir, str(user_id))
    file_path = os.path.join(attachment_user_dir, file_name)
    if not os.path.exists(attachment_dir):
        os.mkdir(attachment_dir)
    if not os.path.exists(attachment_user_dir):
        os.mkdir(attachment_user_dir)
    with open(file_path, 'wb') as f:
        f.write(bytes)
